from celery import Celery
import sys
sys.path.append("/")
from app.models.user import User
from app.schemas.user import users_schema

# 创建Flask应用上下文


celery = Celery(__name__, broker='redis://redis:6379/15', backend='redis://redis:6379/1')

# 使用应用上下文

@celery.task(bind=True, name='tasks.get_all_users')
def get_all_users(self):
    """获取所有用户数据并缓存"""
    from app import create_app  # 延迟导入，避免循环依赖
    import os
    app = create_app(os.getenv('FLASK_ENV') or 'default')

    with app.app_context():
        self.update_state(state='PROGRESS', meta={'progress': 30})

        try:
            # 查询数据库
            users = User.query.all()
            self.update_state(state='PROGRESS', meta={'progress': 70})

            # 转换为字典列表
            users = users_schema.dump(users)

            result = {
                'progress': 100,
                'result': users,
                'count': len(users)
            }

            return result

        except Exception as e:
            self.update_state(state='FAILURE', meta={'error': str(e)})
            raise
